﻿using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Hosting;

namespace EF_Brave.Service.Logging.Service
{
    public class Log4NetLoggerFactoryAdapter : ILoggerFactoryAdapter
    {
        private static bool _isConfigLoaded = false;

        /// <summary>
        /// 构造函数（默认加载"~/configs/log4net.config"作为log4net配置文件）
        /// </summary>
        public Log4NetLoggerFactoryAdapter()
            : this("~/log4net.config")
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configFilename">
        /// <remarks>
        /// <para>log4net配置文件路径，支持以下格式：</para>
        /// <list type="bullet">
        /// <item>~/config/log4net.config</item>
        /// <item>~/web.config</item>
        /// <item>c:\abc\log4net.config</item>
        /// </list>
        /// </remarks>
        /// </param>
        public Log4NetLoggerFactoryAdapter(string configFilename)
        {
            if (!_isConfigLoaded)
            {
                if (string.IsNullOrEmpty(configFilename))
                {
                    configFilename = "~/log4net.config";
                }
                var configFileInfo = new FileInfo(GetPhysicalFilePath(configFilename));
                if (!configFileInfo.Exists)
                {
                    throw new ApplicationException(string.Format("log4net配置文件 {0} 未找到", configFileInfo.FullName));
                }
                XmlConfigurator.ConfigureAndWatch(configFileInfo);
                _isConfigLoaded = true;
            }
        }

        /// <summary>
        /// 依据LoggerName获取
        /// </summary>
        /// <param name="loggerName">日志名称（例如：log4net的logger配置名称）</param>
        /// <returns></returns>
        public ILogger GetLogger(string loggerName)
        {
            return new Log4NetLogger(LogManager.GetLogger(loggerName));
        }


        /// <summary>
        /// 获取物理文件路径
        /// </summary>
        /// <param name="filePath">
        /// <remarks>
        /// <para>filePath支持以下格式：</para>
        /// <list type="bullet">
        /// <item>~/abc/</item>
        /// <item>c:\abc\</item>
        /// <item>\\192.168.0.1\abc\</item>
        /// </list>
        /// </remarks>
        /// </param>
        /// <returns>
        /// </returns>
        public static string GetPhysicalFilePath(string filePath)
        {
            string calculatedFilePath = null;


            if ((filePath.IndexOf(":\\") != -1) || (filePath.IndexOf("\\\\") != -1))
            {
                calculatedFilePath = filePath;
            }
            else
            {
                if (HostingEnvironment.IsHosted)
                {
                    calculatedFilePath = HostingEnvironment.MapPath(filePath);
                }
                else
                {
                    filePath = filePath.Replace('/', Path.DirectorySeparatorChar).Replace("~", string.Empty);
                    calculatedFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
                }
            }
            return calculatedFilePath;
        }
    }
}
